package com.ruxiaoxin.share.util.shiro;

import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.ruxiaoxin.share.domain.user.User;
import com.ruxiaoxin.share.service.user.UserService;

/**
 * 根据本项目业务重新实现shiro认证与授权
 * 
 * @author ruxiaoxin
 */
@Transactional
public class ShiroRealm extends AuthorizingRealm {
	@Autowired
	private UserService userService;

	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		String username = (String) principals.fromRealm(getName()).iterator()
				.next();
		User user = userService.getByEmail(username);
		if (null != user) {
			try {
				Set<String> roles = user.getRolesAsString();
				Set<String> permission = user.getPermissionesAsString();
				SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
				authorizationInfo.setRoles(roles);
				authorizationInfo.setStringPermissions(permission);
				return authorizationInfo;
			} catch (Exception e) {
				throw new AuthenticationException(
						"the exception happen during authorization");
			}
		} else {
			return null;
		}

	}

	/**
	 * 认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken uptoken = (UsernamePasswordToken) token;
		String username = uptoken.getUsername();
		if (StringUtils.isBlank(username)) {
			throw new RuntimeException("username is null");
		}
		User user = userService.getByEmail(username);
		if (null == user) {
			throw new RuntimeException("user is null");
		}
		return new SimpleAuthenticationInfo(username, user.getPassword()
				.toCharArray(), getName());

	}

}
